<!-- src/App.vue -->
<template>
  <div class="app-container">
    <h3>待办清单</h3>
    <AddTodo @add-task="addTask" />
    <TodoList
      :tasks="tasks"
      @update-task="toggleTaskStatus"
      @delete-task="deleteTask"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import AddTodo from './components/AddTodo.vue';
import TodoList from './components/TodoList.vue';

// 从本地存储加载任务（初始化）
const tasks = ref(JSON.parse(localStorage.getItem('tasks')) || []);

// 监听任务列表变化，同步到本地存储
watch(tasks, (newTasks) => {
  localStorage.setItem('tasks', JSON.stringify(newTasks));
}, { deep: true });

// 添加新任务
const addTask = (text) => {
  if (text.trim()) {
    tasks.value.push({ text: text.trim(), done: false });
  }
};

// 切换任务完成状态（核心方法）
const toggleTaskStatus = (index) => {
  // 确保索引有效
  if (index >= 0 && index < tasks.value.length) {
    // 直接修改原对象的 done 属性（Vue 能检测到这种变化）
    tasks.value[index].done = !tasks.value[index].done;
  }
};

// 删除任务
const deleteTask = (index) => {
  tasks.value.splice(index, 1);
};
</script>

<style>
/* 保持原样式不变 */
.app-container {
  max-width: 400px;
  margin: 20px auto;
  font-family: sans-serif;
}
input {
  width: 300px;
  padding: 5px;
}
button {
  padding: 5px 10px;
  background: #007bff;
  color: white;
  border: none;
  cursor: pointer;
}
#list {
  list-style: none;
  padding: 0;
  margin-top: 10px;
}
#list li {
  padding: 8px;
  margin: 5px 0;
  background: #f0f0f0;
  display: flex;
  justify-content: space-between;
}
#list li.done {
  text-decoration: line-through;
  color: #666;
}
.del {
  background: #dc3545;
  padding: 2px 6px;
}
</style>